/*
 * Copyright 2002-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hsc.lock.annotation;

import com.hsc.lock.config.LockManagementConfigUtils;
import com.hsc.lock.interceptor.BeanFactoryLockOperationSourceAdvisor;
import com.hsc.lock.interceptor.LockInterceptor;
import com.hsc.lock.interceptor.OperationSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * {@code @Configuration} class that registers the Spring infrastructure beans necessary
 * to enable proxy-based annotation-driven lock management.
 *
 * @author Chris Beams
 * @author Juergen Hoeller
 * @see EnableCaching
 * @see CachingConfigurationSelector
 * @since 3.1
 */
@Configuration
public class ProxyLockConfiguration extends AbstractCachingConfiguration {

    @Bean(name = LockManagementConfigUtils.LOCK_ADVISOR_BEAN_NAME)
    public BeanFactoryLockOperationSourceAdvisor lockAdvisor() {
        BeanFactoryLockOperationSourceAdvisor advisor = new BeanFactoryLockOperationSourceAdvisor();
        advisor.setCacheOperationSource(lockOperationSource());
        advisor.setAdvice(lockInterceptor());
        if (this.enableReplayLock != null) {
            advisor.setOrder(this.enableReplayLock.<Integer>getNumber("order"));
        }
        return advisor;
    }

    @Bean
    public OperationSource lockOperationSource() {
        return new AnnotationLockOperationSource();
    }

    @Bean
    public LockInterceptor lockInterceptor() {
        LockInterceptor interceptor = new LockInterceptor();
        interceptor.configure(this.errorHandler, this.keyGenerator, this.refuseEnterHandler, this.lockStore);
        interceptor.setLockOperationSource(lockOperationSource());
        return interceptor;
    }

}
